package com.dreamsail.core.frame;

import com.alibaba.fastjson.JSONObject;
import com.dreamsail.core.constant.ErrorMessage;
import com.dreamsail.core.model.system.BaseException;
import com.dreamsail.core.model.system.HeadMessage;
import com.dreamsail.core.model.system.Result;
import com.dreamsail.core.model.system.UserTokenInfo;
import com.dreamsail.core.util.JwtUtil;
import com.dreamsail.core.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LoginRegistry implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            SkipLogin skipLogin = method.getAnnotation(SkipLogin.class);
            if (skipLogin != null) {
                return true;
            }
        }else{
            return true;
        }

        HeadMessage headMessage = new HeadMessage();
        String requestId = request.getHeader("request_id");
        if (requestId == null) {
            headMessage.setRequestId(UUIDUtil.getUUIDStr());
        } else {
            headMessage.setRequestId(requestId);
        }

        String token = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(token)) {
            try {
                UserTokenInfo userTokenInfo = JwtUtil.parseUserInfo(token,response);
                headMessage.setUserId(userTokenInfo.getUserId());
                headMessage.setUserName(userTokenInfo.getAccount());
            }catch (Exception e){
                // 登录过期
                Result notLogin = new Result(ErrorMessage.LOGIN_OUT.getCode(), ErrorMessage.LOGIN_OUT.getMsg(), null);
                response.setStatus(401);
                response.getWriter().write(JSONObject.toJSONString(notLogin));
                return false;
            }
        } else {
            // 未登录
            Result notLogin = new Result(ErrorMessage.NEED_LOGIN.getCode(), ErrorMessage.NEED_LOGIN.getMsg(), null);
            response.getWriter().write(JSONObject.toJSONString(notLogin));
            return false;
        }
        ContentManager.setHeadMessage(headMessage);
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        ContentManager.clear();
    }
}
